<?php
/*
 * ftp处理类
 * @package    system
 * @author     Mark
 * @copyright  Copyright (c) 2013 ixdcw team
 * @version    $Id: 81f61f6734b9d039e8485705dc09a56e5035ac33 $
 */
defined('IN_IXDCW') or exit('Access Denied');
/**
 * ftp类
 */
class MkFtp {
	private $_fp;
	private $_root;
	private $_connected = 0;

	/**
	 * constructor
	 * @param        $ftphost
	 * @param        $ftpuser
	 * @param        $ftppass
	 * @param int    $ftpport
	 * @param string $root
	 * @param int    $pasv
	 * @param int    $ssl
	 */
	function __construct($ftphost, $ftpuser, $ftppass, $ftpport = 21, $root = '/', $pasv = 0, $ssl = 0) {
		if($ssl && function_exists('ftp_ssl_connect')) {
			$this->_fp = @ftp_ssl_connect($ftphost, $ftpport);
		} else if(function_exists('ftp_connect')) {
			$this->_fp = @ftp_connect($ftphost, $ftpport);
		} else {
			return false;
		}
		$this->_connected = @ftp_login($this->_fp, $ftpuser, $ftppass);
		@ftp_pasv($this->_fp, $pasv);
		$this->_root = File::dirPath($root);
	}

	function chdir($dir = '') {
		return @ftp_chdir($this->_fp, $this->_root.$dir);
	}

	function chmod($path, $mode = 0777) {
		$path = $this->_root.$path;
		return function_exists('ftp_chmod') ? @ftp_chmod($this->_fp, $mode, $path) : @ftp_site($this->_fp, "CHMOD $mode $path");
	}

	function mkdir($dir, $mode = 0777) {
		$temp = explode('/', $dir);
		$cur_dir = '';
		$max = count($temp);
		for($i = 0; $i < $max; $i++) {
			$cur_dir .= $temp[$i].'/';
			if($this->chdir($cur_dir)) continue;
			@ftp_mkdir($this->_fp, $this->_root.$cur_dir);
			$this->chmod($cur_dir, $mode);
		}
		return $this->chdir($dir);
	}

	function rmdir($dir) {
		return @ftp_rmdir($this->_fp, $this->_root.$dir);
	}

	function delete($file) {
		return @ftp_delete($this->_fp, $this->_root.$file);
	}

	function put($local, $remote = '') {
		$remote or $remote = $local;
		$local = DT_ROOT.'/'.$local;
		$this->mkdir(dirname($remote));
		if(@ftp_put($this->_fp, $this->_root.$remote, $local, FTP_BINARY)) {
			$this->chmod($remote);
			return true;
		} else {
			return false;
		}
	}
}